package com.banyuan.servlet;

import com.alibaba.fastjson.JSON;
import com.banyuan.domain.ReturnJson;
import com.banyuan.util.JDBCUtil;

import javax.lang.model.element.VariableElement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

/**
 * @author 陶继发
 * @version 1.8
 */
@SuppressWarnings("all")
@WebServlet("/translate")
public class Translate  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Connection connection = null;
        ResultSet re = null;
        StringBuffer sb = new StringBuffer();
        try {
             connection = JDBCUtil.getConnection();
            String jian = req.getParameter("jianti");
            String sql = "select * from translate where jianti=?";
            for (int i = 0; i < jian.length(); i++) {
                String s = String.valueOf(jian.charAt(i));
                re = JDBCUtil.executeQuery(connection, sql, s);
                if(re.next()){
                     String fan = re.getString("fanti");
                     sb.append(fan);
                 }else {
                     sb.append(s);
                 }

            }
            ReturnJson returnJson = new ReturnJson();
            returnJson.setFan(sb.toString());
            String fanJson = JSON.toJSONString(returnJson);
            resp.getWriter().print(fanJson);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                Statement statement = re.getStatement();
                JDBCUtil.close(statement);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            JDBCUtil.close(re);
            JDBCUtil.close(connection);
        }

    }
}
